import axios from 'axios'
import router from '@/router'
import { Message, Loading, MessageBox } from 'element-ui'
import { getToken } from './cookie'
import store from '@/store'

const request = axios.create({
  baseURL: '',
  timeout: 5000
})
let loading = null
request.interceptors.request.use(
  (config) => {
    loading = Loading.service({
      lock: true,
      text: 'loading...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    if (store.getters.token) {
      config.headers['C-Token'] = getToken()
    }
    return config
  },
  (error) => {
    loading.close()
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    const res = response.data
    loading.close()
    // 50000 表示token失效
    if (res.errcode === 50000) {
      MessageBox.confirm(res.msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          router.push('/login')
        })
      })
    } else {
      return res
    }
  },
  (error) => {
    loading.close()
    Message({
      message: error.errmsg,
      type: 'error'
    })
    return Promise.reject(error)
  }
)

export default request
